package com.lc.servlet;

import com.lc.bean.Menu;
import com.lc.bean.Users;
import com.lc.service.UsersService;
import com.lc.service.impl.UsersServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @description:用于进行用户登录操作的servlet
 * @author: ManolinCoder
 * @time: 2021/8/22
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.接收参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2.调取service
        UsersService usersService = new UsersServiceImpl();
        Users users = usersService.login(username, password);

        //3.跳转页面
        if (users == null){
            //登录失败以弹窗方式提示
            resp.setContentType("text/html;charset=utf-8");
            PrintWriter writer = resp.getWriter();
            writer.println("<script>location.href='login.jsp';alert('用户名或密码错误');</script>");
        }else {
            //登录成功跳转到主页面
            //保存用户信息
            HttpSession session = req.getSession();
            session.setAttribute("currentUser",users);
            resp.sendRedirect("index.jsp");
        }
    }
}
